from fastapi import Request
from fastapi.responses import FileResponse, StreamingResponse
import os

from service import UserService, SongService
from common.result.Result import Result
from common.enum import BaseEnum
from util.log import Log
from util.str import Str
from util.token import MusicToken

class Body:
    id: int
    secretKey: str

async def GetSongResource(req: Request, id: int, secretKey: str):
    try:
        if Str.isBlank(id, secretKey):
            return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)
        
        payload = MusicToken().verify_token(secretKey)
        if payload == None:
            return Result.error(BaseEnum.INVALID_SECRETKEY_ERROR)
        
        songId = payload.get('songId')
        if songId != id:
            return Result.error(BaseEnum.INVALID_PAYLOAD_ERROR)
        
        song = await SongService.getSongById(songId)
        if song == None:
            return Result.error(BaseEnum.SONG_NOT_EXIST_ERROR)

        rootpath = os.path.realpath(os.curdir)
        filepath = os.path.join(rootpath, "upload_file", song.singer + ' - ' + song.name + song.ext)

        if song.ext == '.mp3':
            return FileResponse(filepath, filename=(song.md5 + song.ext), media_type="audio/mpeg")
        else:
            return FileResponse(filepath, filename=(song.md5 + song.ext), media_type="audio/ogg")
        # fp = open(filepath, mode='rb')
        # return StreamingResponse(content=fp, media_type='audio/mp3')
    except Exception as e:
        Log.error('获取 song 的播放资源异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)
    



